<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>聊天室应用</title>
<style type="text/css">
    #container{width:800px;height:560px;margin:0 auto;margin-top:30px;}
    .title{text-align:center;background-color:pink;}
    .title a {float:right;}
    .body-content{width:height:360px;background-color:pink;}
    .left{width:600px;float:left;height:250px;}
    .right{width:200px;float:right;height:300px;}
    .content{height:280px;}
    .content textarea{width:100%;height:100%;}
    .btnSend{height:120px;padding-top:10px;}
    #message{width:600px;}
    .right ul {list-style-type:none;}
</style>
<script type="text/javascript" src="js/jquery-1.10.2.js"></script>
<script type="text/javascript">
	/* 	   
	 if (typeof String.prototype.startsWith != 'function') {
	    String.prototype.startsWith = function (str){
	       return this.slice(0, str.length) == str;
	    };
	  }

	  if (typeof String.prototype.endsWith != 'function') {
	    String.prototype.endsWith = function (str){
	       return this.slice(-str.length) == str;
	    };
	  } */

	var Chat = {};
	Chat.socket = null;
	Chat.connect = (function(host) {
	    if ('WebSocket' in window) {
	        Chat.socket = new WebSocket(host);
	    } else if ('MozWebSocket' in window) {
	        Chat.socket = new MozWebSocket(host);
	    } else {
	        Console.log('Error: WebSocket is not supported by this browser.');
	        return;
	    }
	    Chat.socket.onopen = function () {
	        Console.log('Info: WebSocket connection opened.');
	        Chat.userList();//获取所有的用户列表
	        document.getElementById('message').onkeydown = function(event) {
	            if (event.keyCode == 13) {
	                Chat.sendMessage();
	            }
	        };
	    };
	
	    Chat.socket.onclose = function () {
	        document.getElementById('message').onkeydown = null;
	        Console.log('Info: WebSocket closed.');
	    };
	
	    Chat.socket.onmessage = function (message) {
	    	//判断信息是否是以s:开头的心想，是这是系统信息，否则为普通信息
	    	if (message.data.slice(0,"in:".length) =="in:"){//处理用户登录广播信息
	    		username =message.data.substring("in:".length,message.data.length)
	    		Console.log(username+"进入聊天室");
	    		Chat.LoginUser(username);
	    	}else if (message.data.slice(0,"out:".length) =="out:"){//处理用户退出的广播信息
	    		username =message.data.substring("out:".length,message.data.length)
	    		Console.log(username+"退出聊天室");
	    		Chat.LoginoutUser(username);
	    	}else{
	    		Console.log(message.data);
	    	}
	    };
	});
	
	Chat.initialize = function() {
	    if (window.location.protocol == 'http:') {
	        Chat.connect('ws://localhost:8080/ws');
	    } else {
	        Chat.connect('wss://localhost:8080/ws');
	    }
	};
	
	Chat.sendMessage = (function() {
	    var message = document.getElementById('message').value;
	    if (message != '') {
	        Chat.socket.send(message);
	        document.getElementById('message').value = '';
	    }
	});
	
	Chat.userList = function(){
		 $.ajax( {  
		     url:'/user/list',// 跳转到 action  
			 data:{}, 
			 type:'post',  
		     cache:false,  
		     dataType:'json',
		     success:function(data) {
		    	 Chat.bindData(data);
		     },
		     error : function() {  
		           alert("异常！");  
		     }
	      });
	};
	
	Chat.LoginoutUser = function(){
		var lis = $(".right ul").children("li");
	   for (var i=0;i<lis.length;i++){
			if (username == lis[i].innerHTML){
				$(lis[i]).remove();//删除子元素
				break;
			}
	   }
	}
	
	Chat.LoginUser = function(username){
		var lis = $(".right ul").children("li");
	    var isExist = false;
		   for (var i=0;i<lis.length;i++){
				if (username == lis[i].innerHTML){
					isExist = true;
					break;
				}
		   }
		   if (!isExist)
			  $(".right ul").append("<li style='color:red;'>"+username+"</li>")
	}
	
	Chat.bindData = function(data){
		var lis = $(".right ul").children("li");
		    var isExist = false;
			for (index in data){
			   var username=data[index].username;//用户名
			   for (var i=0;i<lis.length;i++){
				if (username == lis[i].innerHTML){
					isExist = true;
					break;
				}
			   }
			   if (!isExist)
				   $(".right ul").append("<li style='color:red;'>"+username+"</li>")
		    }
		console.log(data);
	}
	
	var Console = {};
	
	Console.log = (function(message) {
	    var console = document.getElementById('console');
	    var oldMessage = console.value;
	    if (oldMessage!=null&&oldMessage.length!=0||message){
	    	console.value = oldMessage+"\n"+message;
	    }
	});
	
	Chat.initialize();
	
	document.addEventListener("DOMContentLoaded", function() {
	    var noscripts = document.getElementsByClassName("noscript");
	    for (var i = 0; i < noscripts.length; i++) {
	        noscripts[i].parentNode.removeChild(noscripts[i]);
	    }
	}, false);
	
</script>
</head>
<body>
	<div id="container">
		 <div class="title">聊天室<a href="/user/logout">退出</a></div>
		 <div class="body-content">
		    <div class="left">
		       <div class="content">
		          <textarea rows="8" id="console" cols="30"></textarea>
		       </div>
		       <div class="btnSend">
		          <input type="text" id="message" placeholder="键入信息后回车发送" name="message"/>
		       </div>
		    </div>
		 	<div class="right">
		 	   <ul>
		 	   </ul>
		 	</div>
		 </div>
	</div>
</body>
</html>